import React, { Component } from 'react'
import { connect } from 'react-redux' // 三步
import axios from 'axios'
import NewsItem from './components/newsItem'
import MyTabs from './components/tab'
import withRouter from '../../utils/withRouter'
import { actionCreator } from '../../store/combineReducer/news'
// 1. 拿数据 state
// 2. 提交命令 dispatch

/**
 * reduce: 减少  return
 *countArr.reduce((任意值, 每一项) => {
  // return 任意值
 }, 任意值)
 *
 */

// const arr = [1, 2, 3, 3, 3, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8, 9] // 1 + 2 + 3
// const res = arr.reduce((nums, item) => {
//   return nums + item
// }, 0)
// // 去重
// const brr = arr.reduce((noRepeatArr, item) => {
//   noRepeatArr.indexOf(item) === -1 && noRepeatArr.push(item)
//   return noRepeatArr
// }, [])

// arr.reduce(() => {}, { index: 5, arr: [] })

// console.log(brr, 'brr')

// console.log(res, 'res')

class News extends Component {
  componentDidMount() {
    this.fetchNewsHeader()
    this.fetchNewsList()
  }

  // 头部接口
  async fetchNewsHeader() {
    this.props.dispatch(actionCreator.initNews())
  }

  // tab切换接口
  async fetchNewsList(type = 'headline') {
    this.props.dispatch(actionCreator.initNewsData(type))
  }

  render() {
    const {
      dispatch,
      news: { newsList, headerArr },
    } = this.props

    return (
      <div>
        <MyTabs
          headerArr={headerArr}
          handleTabClick={(key) => {
            console.log('key:', key)
            this.fetchNewsList(key)
          }}
        >
          <NewsItem newsList={newsList} />
        </MyTabs>
      </div>
    )
  }
}

export default connect(
  (state) => {
    return { ...state }
  },
  (dispatch) => {
    return { dispatch }
  }
)(withRouter(News))
